package com.idlecode.service;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.idlecode.bean.DataSourceEntity;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-02-06 09:37
 **/
public final class DataSourceService {

	private static final String PREF_KEY = "IdleCodeDataSources";

	// 获取插件的首选项存储
	private static Preferences getPreferenceStore() {
		 return InstanceScope.INSTANCE.getNode("com.idlecode");
	}

	// 保存列表数据到首选项存储
	public static void setDataSources(List<DataSourceEntity> dataSources) {
		String dataSourceStr = JSONUtil.toJsonStr(dataSources);
		Preferences store = getPreferenceStore();
		store.put(PREF_KEY, dataSourceStr);
		try {
			store.flush();// 确保首选项保存到磁盘
		} catch (BackingStoreException e) {
			e.printStackTrace();
		} 

	}

	// 从首选项存储中读取列表数据
	public static List<DataSourceEntity> getDataSources() {
		Preferences store = getPreferenceStore();
		String dataSourceStr = store.get(PREF_KEY, "");
		if (StrUtil.isBlank(dataSourceStr)) {
			return new ArrayList<>();
		}
		return JSONUtil.toList(dataSourceStr, DataSourceEntity.class);
	}
}
